package com.key.puzzlemodel.cutterman

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.graphics.drawable.toBitmap
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.key.puzzlemodel.R
import com.key.puzzlemodel.databinding.ActivityCutterManBinding
import com.key.puzzlemodel.dialog.DialogUtil
import com.key.puzzlemodel.mvvm.BaseMVVMActivity
import com.key.puzzlemodel.util.PuzzleAppManager
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 *
 * @功能描述:     宫格切图界面
 * @创建时间:     2022/1/5
 * @创建者:       阳
 * @修改时间:     2022/1/5
 * @修改者:       阳
 */
class CutterManActivity : BaseMVVMActivity<ActivityCutterManBinding, CutterManMVVMViewModel>(),
    View.OnClickListener {

    override val layoutId: Int
        get() = R.layout.activity_cutter_man

    var mBitmap: Bitmap? = null

    var photoPath = ""

    var intentActivityResultLauncher: ActivityResultLauncher<Intent>? = null

    /**
     *  0:纵向 ， 1 ：横向
     */
    var cutterDirection = 0


    override fun initView(savedInstanceState: Bundle?) {
        //添加activity管理
        PuzzleAppManager.getInstance().addActivity(this)

        window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE

        mVDB.clickListener = this

        var startList =
            intent.getStringArrayListExtra(com.key.puzzlemodel.config.PuzzleConfig.START_PHOTO_List) as ArrayList<String>

        photoPath = startList[0]

        Glide.with(this).load(photoPath).into(mVDB.imageCutterMan)


        initTopView()
        mVM.sliceResult.observe(this) {
            // Log.e("切图数据：", "状态== $it")
            DialogUtil.closeDialog()
            if (it) {
                var intent = Intent(this@CutterManActivity, PreviewActivity::class.java)
                intent.putExtra("horizontalPicNumber", mVDB.imageCutterMan.horizontalPicNumber)
                intent.putExtra("verticalPicNumber", mVDB.imageCutterMan.verticalPicNumber)
                intentActivityResultLauncher?.launch(intent)
            }
        }

        intentActivityResultLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                Log.e(
                    "回调处理：",
                    "CutterManActivity -- ${it.data != null}  -- ${it.resultCode == Activity.RESULT_OK}"
                )
                //回调处理
                if (it.resultCode == Activity.RESULT_OK) {
                    it.data?.apply {
                        val mediaPath: ArrayList<String>? =
                            getStringArrayListExtra(com.key.puzzlemodel.config.PuzzleConfig.EDIT_RESULT)

                        setResult(Activity.RESULT_OK, Intent().apply {
                            putExtra(
                                com.key.puzzlemodel.config.PuzzleConfig.EDIT_RESULT,
                                mediaPath
                            )

                            putExtra(
                                com.key.puzzlemodel.config.PuzzleConfig.HOR_PIC_NUMBER,
                                mVDB.imageCutterMan.horizontalPicNumber
                            )
                            putExtra(
                                com.key.puzzlemodel.config.PuzzleConfig.VER_PIC_NUMBER,
                                mVDB.imageCutterMan.verticalPicNumber
                            )
                        })
                        this@CutterManActivity.finish()
                    }
                }
            }


    }

    private fun initTopView() {
        findViewById<TextView>(R.id.txt_cutter_man_top_title).text =
            getString(R.string.cutter_man_title)
        findViewById<ImageView>(R.id.image_cutter_man_return).setOnClickListener {
            onBackPressed()
        }

        //导出按钮
        val txtSave = findViewById<TextView>(R.id.txt_cutter_man_top_title_right)
        txtSave.visibility = View.VISIBLE
        txtSave.text = getString(R.string.string_preview)
        txtSave.setOnClickListener {
            DialogUtil.showLoading(this)
            doSliceList()
        }
    }


    override fun onClick(view: View) {
        when (view.id) {
            R.id.relayout_cutter_man_item_9 -> {
                setImageViewSquaresNumber(3, 3, mVDB.imgCutterManItem9)
            }

            R.id.relayout_cutter_man_item_6 -> {
                setImageViewSquaresNumber(3, 2, mVDB.imgCutterManItem6)
            }

            R.id.relayout_cutter_man_item_4 -> {
                setImageViewSquaresNumber(2, 2, mVDB.imgCutterManItem4)
            }

            R.id.relayout_cutter_man_item_3 -> {
                setImageViewSquaresNumber(3, 1, mVDB.imgCutterManItem3)
            }

            R.id.img_cutter_man_vertical -> {
                setCutterManImageBackground(0)
            }
            R.id.img_cutter_man_horizontal -> {
                setCutterManImageBackground(1)
            }
        }
    }

    private fun setImageViewSquaresNumber(horNumber: Int, verNumber: Int, imageView: ImageView) {
        mVDB.imgCutterManItem9.background = null
        mVDB.imgCutterManItem6.background = null
        mVDB.imgCutterManItem4.background = null
        mVDB.imgCutterManItem3.background = null
        mVDB.imageCutterMan.setSquaresNumber(horNumber, verNumber)

        //设置背景
        imageView.setBackgroundResource(R.drawable.cutter_man_radio_bg)

        lifecycleScope.launch {
            delay(100)
            setCutterManImageBackground(cutterDirection)
        }
    }


    /**
     * 设置横纵向的背景显示
     * 0:纵向 ， 1 ：横向
     */
    private fun setCutterManImageBackground(direction: Int) {
        if (0 == direction) {
            mVDB.imgCutterManVertical.setBackgroundResource(R.drawable.cutter_man_radio_5_bg)
            mVDB.imgCutterManHorizontal.setBackgroundResource(R.color.color202225)
        } else {
            mVDB.imgCutterManHorizontal.setBackgroundResource(R.drawable.cutter_man_radio_5_bg)
            mVDB.imgCutterManVertical.setBackgroundResource(R.color.color202225)
        }
        mBitmap = mVDB.imageCutterMan.drawable.toBitmap()
        cutterDirection = direction
        mVDB.imageCutterMan.setImageMatrixLayout(direction)
    }


    private fun doSliceList() {

        mVDB.imageCutterMan.isDrawingCacheEnabled = true
        mVDB.imageCutterMan.buildDrawingCache(true)

        var obmp = Bitmap.createBitmap(mVDB.imageCutterMan.drawingCache);
        mVDB.imageCutterMan.isDrawingCacheEnabled = false

        val PIC_BORDER_LEN = mVDB.imageCutterMan.itemWidth.toInt()
        val PIC_DIVIDER_LEN = 24

        val srcW: Int = obmp.width
        val srcH: Int = obmp.height

        val hNum: Int = mVDB.imageCutterMan.horizontalPicNumber
        val vNum: Int = mVDB.imageCutterMan.verticalPicNumber


        val mAspectX = PIC_BORDER_LEN * hNum + PIC_DIVIDER_LEN * (hNum - 1)
        val mAspectY = PIC_BORDER_LEN * vNum + PIC_DIVIDER_LEN * (vNum - 1)

        val picW: Int = srcW * PIC_BORDER_LEN / mAspectX
        val picH: Int = srcH * PIC_BORDER_LEN / mAspectY

        val dividerW: Int = srcW * PIC_DIVIDER_LEN / mAspectX
        val dividerH: Int = srcH * PIC_DIVIDER_LEN / mAspectY


        CutterManConfig.bitmaps = ArrayList()
        for (j in 0 until vNum) {
            for (i in 0 until hNum) {
//                val bitmap = Bitmap.createBitmap(
//                    obmp,
//                    (mVDB.imageCutterMan.itemWidth * i).toInt(),
//                    (mVDB.imageCutterMan.itemHeight * j).toInt(),
//                    mVDB.imageCutterMan.itemWidth.toInt(),
//                    mVDB.imageCutterMan.itemHeight.toInt()
//                )
                val bitmap = Bitmap.createBitmap(
                    obmp,
                    (picW + dividerW) * i,
                    (picH + dividerH) * j,
                    picW,
                    picH
                )
                CutterManConfig.bitmaps.add(bitmap)
            }
        }

        mVM.sliceResult.value = true
    }


}

/**
 *     /**
 * 图片等比例铺满宫格的顶部和底部并左右居中展示
*/
private fun setTopToBottom() {
mVDB.imageCutterMan.scaleType = ImageView.ScaleType.MATRIX

var viewWidth = mVDB.imageCutterMan.measuredWidth
var viewHeight = mVDB.imageCutterMan.measuredHeight
Log.e("view 的宽高", "viewWidth == $viewWidth  viewHeight == $viewHeight")
if (viewWidth <= 0 || viewHeight <= 0 || null == mBitmap) {
return
}
var ratio = viewHeight * 1.0f / mBitmap!!.height
var dx = (viewWidth - mBitmap!!.width) * 1.0f / 2
var dy = (viewHeight - mBitmap!!.height) * 1.0f / 2


//进行缩放限制
if (ratio >= 4.0f) {
ratio = 4.0f
}
if (ratio <= 0.3f) {
ratio = 0.3f
}


var imageMatrix = Matrix()
//设置缩放
imageMatrix.setScale(
ratio,
ratio,
(mBitmap!!.width / 2).toFloat(),
(mBitmap!!.height / 2).toFloat()
)
//图片移动
imageMatrix.postTranslate(dx, dy)
mVDB.imageCutterMan.imageMatrix = imageMatrix
//        //设置缩放
//        mVDB.imageCutterMan.imageMatrix.setScale(
//            ratio,
//            ratio,
//            (mBitmap!!.width / 2).toFloat(),
//            (mBitmap!!.height / 2).toFloat()
//        )
//        //图片移动
//        mVDB.imageCutterMan.imageMatrix.postTranslate(dx, dy)

//存储信息
mVDB.imageCutterMan.setImageLocation(ratio, dx, dy)

mVDB.imageCutterMan.invalidate()
}


/**
 * 图片等比例铺满宫格的左边和右边并上下居中展示
*/
private fun setLeftToRight() {
mVDB.imageCutterMan.scaleType = ImageView.ScaleType.MATRIX

var viewWidth = mVDB.imageCutterMan.measuredWidth
var viewHeight = mVDB.imageCutterMan.measuredHeight
if (viewWidth <= 0 || viewHeight <= 0 || null == mBitmap) {
return
}

var ratio = 1.0f * viewWidth / mBitmap!!.width
//进行缩放限制
if (ratio >= 4.0f) {
ratio = 4.0f
}
if (ratio <= 0.3f) {
ratio = 0.3f
}

var dx = (viewWidth - mBitmap!!.width) * 1.0f / 2
var dy = (viewHeight - mBitmap!!.height) * 1.0f / 2

var imageMatrix = Matrix()
//设置缩放
imageMatrix.setScale(
ratio,
ratio,
(mBitmap!!.width / 2).toFloat(),
(mBitmap!!.height / 2).toFloat()
)
//图片移动
imageMatrix.postTranslate(dx, dy)

mVDB.imageCutterMan.imageMatrix = imageMatrix
//设置缩放
//        mVDB.imageCutterMan.imageMatrix.setScale(
//            ratio,
//            ratio,
//            (mBitmap!!.width / 2).toFloat(),
//            (mBitmap!!.height / 2).toFloat()
//        )
//        //图片移动
//        mVDB.imageCutterMan.imageMatrix.postTranslate(dx, dy)

//存储信息
mVDB.imageCutterMan.setImageLocation(ratio, dx, dy)
mVDB.imageCutterMan.invalidate()

}

 */